package com.bocloud.cmp.service.resource;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bocloud.cmp.dao.CloudServerDao;
import com.bocloud.cmp.dao.ServerDao;
import com.bocloud.cmp.entity.resource.CloudServer;
import com.bocloud.cmp.entity.resource.Server;
import com.bocloud.cmp.interfaces.resource.StatisticService;
import com.bocloud.cmp.service.model.Computerstat;
import com.bocloud.cmp.service.model.StatsResult;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;

/**
 * 
 * @author song song
 * @since 2017.02.27
 *
 */
@Service("StatisticService")
public class StatisticServiceImpl implements StatisticService {

	private static Logger logger = LoggerFactory.getLogger(StatisticServiceImpl.class);
	@Autowired
	private ServerDao serverDao;
	@Autowired
	private CloudServerDao cloudServerDao;

	@Override
	public BsmResult compute() {
		try {
			List<StatsResult> host = Lists.newArrayList();
			// 查询所有的物理机
			List<Server> servers = serverDao.queryAll();
			// 查询所有的虚拟机
			List<CloudServer> cloudServers = cloudServerDao.queryAll();

			// 物理机开机数量
			int hostOnlines = 0;
			// 物理机关机数量
			int hostOfflines = 0;
			// 物理机异常数量
			int hostErrors = 0;
			for (Server server : servers) {// 遍历所有的物理机
				if (server.getStatus().equalsIgnoreCase("RUNNING")) {
					hostOnlines++;
				} else if (server.getStatus().equalsIgnoreCase("STOPPED")) {
					hostOfflines++;
				} else if (server.getStatus().equalsIgnoreCase("EXCEPTION")) {
					hostErrors++;
				}
			}
			host.add(new StatsResult("onlines", hostOnlines));
			host.add(new StatsResult("offlines", hostOfflines));
			host.add(new StatsResult("errors", hostErrors));
			host.add(new StatsResult("instances", servers.size()));

			List<StatsResult> server = Lists.newArrayList();
			// 虚拟机开机数
			int serverOnlines = 0;
			// 虚拟机关机数
			int serverOfflines = 0;
			// 虚拟机异常数量
			int serverErrors = 0;
			for (CloudServer cloudServer : cloudServers) {// 遍历所有的虚拟机
				if (cloudServer.getStatus().equalsIgnoreCase("RUNNING")) {
					serverOnlines++;
				} else if (cloudServer.getStatus().equalsIgnoreCase("STOPPED")) {
					serverOfflines++;
				} else if (cloudServer.getStatus().equalsIgnoreCase("EXCEPTION")) {
					serverErrors++;
				}
			}
			server.add(new StatsResult("onlines", serverOnlines));
			server.add(new StatsResult("offlines", serverOfflines));
			server.add(new StatsResult("errors", serverErrors));
			server.add(new StatsResult("instances", cloudServers.size()));

			// 统计数据
			Computerstat stat = new Computerstat(host, server);
			return new BsmResult(true, stat, "查询数据成功");
		} catch (Exception e) {
			logger.error("query statistic failure:", e);
			return new BsmResult(false, "查询数据失败");
		}
	}
}
